
// https://leetcode.cn/problems/minesweeper/

class Solution
{
    int m, n;
    int dx[8] = { 0, 0, 1, -1, 1, 1, -1, -1 };
    int dy[8] = { 1, -1, 0, 0, 1, -1, 1, -1 };
    vector<vector<int>> used;

public:
    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click)
    {
        m = board.size();
        n = board[0].size();
        used = vector<vector<int>>(m, vector<int>(n, 0));
        int x = click[0];
        int y = click[1];
        if (board[x][y] == 'M')
        {
            board[x][y] = 'X';
            return board;
        }

        dfs(board, x, y);
        return board;
    }

    void dfs(vector<vector<char>>& board, int i, int j)
    {
        int cnt = get_cnt(board, i, j);
        used[i][j] = 1;
        if (cnt == 0)
        {
            board[i][j] = 'B';
            for (int k = 0; k < 8; ++k)
            {
                int x = i + dx[k];
                int y = j + dy[k];
                if (x >= 0 && x < m && y >= 0 && y < n && used[x][y] == 0)
                    dfs(board, x, y);
            }
        }
        else
        {
            board[i][j] = cnt + '0';
        }
    }

    int get_cnt(vector<vector<char>>& board, int i, int j)
    {
        int cnt = 0;
        for (int k = 0; k < 8; ++k)
        {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M')
                ++cnt;
        }
        return cnt;
    }
};